# 一个简单的TCP服务器的实现，它使用Python的socket库来监听客户端连接，并尝试根据接收到的消息发送文件内容给客户端
import socket
import os

serverPort = 50008
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverSocket.bind(('127.0.0.1', serverPort))
serverSocket.listen(1)
print('The server is ready to receive')

while True:
    connectionSocket, addr = serverSocket.accept()
    try:
        sentence = connectionSocket.recv(1024).decode()  # 接收并解码客户端消息为字符串
        ans = ''
        flag = False
        print("sentenct",sentence)
        for ch in sentence:
            print("ch",ch)
            if ch == ' ' and flag:
                break
            if flag:
                ans += ch
            elif ch == ' ':
                flag = True
        
        path = '.' + ans
        print(path)
        if not os.path.exists(path):
            response = '404 Not Found'
            connectionSocket.sendall(response.encode() + b'\r\n')  # 发送404错误信息，编码为字节串
        else:
            with open(path, 'rb') as file:  # 以二进制模式打开文件
                while True:
                    data = file.read(1024)
                    if not data:
                        break
                    connectionSocket.sendall(data)  # 直接发送文件内容，已经是字节形式
    except Exception as e:
        print(f"Error handling request: {e}")
    finally:
        connectionSocket.close()

serverSocket.close()